import {
  Button,
  DatePicker,
  Form,
  Input,
  Message,
  Modal,
  Select,
  Space,
} from "@arco-design/web-react";
import { css } from "@emotion/css";
import { FC, useMemo, useState } from "react";
import { Role, Sex, SystemUserDataRow } from "../../api/types/system-user.ts";
import { useMutation, useQuery } from "react-query";
import { SearchBuildingParams } from "../../api/types/building.tsx";
import { useAPI } from "../../hooks/useAPI.ts";
import { encrypt } from "../../utils/encrypt.ts";
import { bedList } from "../BindElderAndRoomModal";
import { bed } from "../../pages/homepage/elderManagement.tsx";
import { SystemUserInfoData } from "../../api/types/system-user-info.ts";
import { IconCheck, IconClose, IconLock } from "@arco-design/web-react/icon";
import { UpdatePasswordModal } from "../UpdatePasswordModal";

export interface EditUserInfoModalProps {
  visible?: boolean;
  onClose?: () => void;
  onSuccess?: () => void;
  title?: string;
  defaultData?: SystemUserDataRow | SystemUserInfoData | null;
  isEditPassword?: boolean;
  isEdit?: boolean;
  isEditElder?: boolean;
  isEditBuilding?: boolean;
}

export const EditUserInfoModal: FC<EditUserInfoModalProps> = ({
  visible,
  onClose,
  title,
  onSuccess,
  isEdit = false,
  isEditPassword = false,
  isEditElder = false,
  isEditBuilding = false,
  defaultData,
}) => {
  const api = useAPI();
  const [formRef] = Form.useForm();
  const selectedBuildingId = Form.useWatch("buildingId", formRef);
  const selectedFloorId = Form.useWatch("floorId", formRef);
  const selectedRoomId = Form.useWatch("roomId", formRef);
  const [isOpenUpdatePasswordModal, setIsOpenUpdatePasswordModal] =
    useState(false);
  const buildingListParams: SearchBuildingParams = {
    pageNum: 1,
    pageSize: 1000,
  };

  const { data: buildingList } = useQuery(
    ["query-building-list", buildingListParams],
    async () => {
      const response = await api.getBuildingList(buildingListParams);
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    },
  );

  const { data: buildingInfo } = useQuery(
    ["query-building-info", selectedBuildingId],
    async () => {
      const response = await api.getBuildingInfoById(selectedBuildingId);
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    },
    {
      enabled: selectedBuildingId !== undefined,
    },
  );

  const rooms = useMemo(() => {
    const floor = buildingInfo?.floors?.find(
      (floor) => floor.id === selectedFloorId,
    );
    if (!floor) return [];
    return floor.rooms;
  }, [buildingInfo?.floors, selectedFloorId]);

  if (defaultData) {
    defaultData.roleIds = defaultData?.roles?.[0]?.roleId;
  }

  const submitForm = useMutation(async () => {
    try {
      const values = await formRef.validate();
      if (isEdit) {
        values.userId = defaultData?.userId;
        values.userName = defaultData?.userName;
        values.location = defaultData?.location;
        values.roleIds = [values.roleIds];
        if (!isEditBuilding) {
          values.buildingId = defaultData?.buildingId;
          values.floorId = defaultData?.floorId;
          values.roomId = defaultData?.roomId;
        }
        await api.updateSystemUser(values);
      } else {
        values.password = encrypt("123456");
        await api.createSystemUser(values);
      }
      if (onSuccess) onSuccess();
      formRef.resetFields();
      Message.success("操作成功");
    } catch (error) {
      if (error instanceof Error) {
        Message.error(error.message);
      } else {
        Message.error("操作失败，请稍后重试");
      }
    }
  });

  // @ts-ignore
  return (
    <Modal
      visible={visible}
      onCancel={() => {
        formRef.resetFields();
        onClose?.();
      }}
      title={title}
      footer={null}
      unmountOnExit
      mountOnEnter
    >
      <UpdatePasswordModal
        visible={isOpenUpdatePasswordModal}
        defaultData={defaultData}
        onClose={() => {
          setIsOpenUpdatePasswordModal(false);
        }}
        onSuccess={() => {
          setIsOpenUpdatePasswordModal(false);
        }}
      />

      {defaultData ? (
        <Form form={formRef} initialValues={defaultData!}>
          <Form.Item
            label="姓名"
            field="nickName"
            rules={[
              {
                required: true,
                message: "姓名不得为空",
              },
            ]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            label="性别"
            field="sex"
            rules={[
              {
                required: true,
                message: "请选择性别",
              },
            ]}
          >
            <Select placeholder="请选择性别">
              <Select.Option value={Sex.Man}>男</Select.Option>
              <Select.Option value={Sex.Woman}>女</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="生日"
            field="birth"
            rules={[
              {
                required: false,
                message: "请选择生日",
              },
            ]}
          >
            <DatePicker placeholder="请选择生日" style={{ width: "380px" }} />
          </Form.Item>

          <Form.Item
            label="角色"
            field="roleIds"
            rules={[
              {
                required: true,
                message: "角色不得为空",
              },
            ]}
          >
            <Select
              placeholder="请选择角色"
              value={defaultData?.roles?.[0]?.roleId}
            >
              <Select.Option value={Role.CommunityLeader}>
                医院办公室
              </Select.Option>
              <Select.Option value={Role.Control}>总值班</Select.Option>
              <Select.Option value={Role.BuildingAdmin}>护理部</Select.Option>
              <Select.Option value={Role.ElderUser}>长辈</Select.Option>
            </Select>
          </Form.Item>

          {isEditBuilding && (
            <>
              <Form.Item
                label="楼栋"
                field="buildingId"
                rules={[
                  {
                    required: true,
                    message: "楼栋不得为空",
                  },
                ]}
              >
                <Select
                  allowClear
                  placeholder="请选择楼栋"
                  options={buildingList?.rows.map((item) => ({
                    label: item.name,
                    value: item.id,
                  }))}
                  onChange={async (value) => {
                    await api.getBuildingInfoById(value!);
                    formRef.setFieldsValue({
                      floorId: undefined,
                      roomId: undefined,
                    });
                  }}
                />
              </Form.Item>
              {isEditElder && (
                <>
                  <Form.Item
                    label="楼层"
                    field="floorId"
                    rules={[
                      {
                        required: true,
                        message: "楼层不得为空",
                      },
                    ]}
                  >
                    <Select
                      allowClear
                      placeholder="请选择楼层"
                      disabled={!selectedBuildingId}
                      options={buildingInfo?.floors?.map((item) => ({
                        label: item.name,
                        value: item.id,
                      }))}
                    />
                  </Form.Item>
                  <Form.Item
                    label="房间号"
                    field="roomId"
                    rules={[
                      {
                        required: true,
                        message: "房间不得为空",
                      },
                    ]}
                  >
                    <Select
                      allowClear
                      placeholder="请选择房间号"
                      disabled={!selectedFloorId}
                      options={rooms?.map((item) => ({
                        label: item.name,
                        value: item.id,
                      }))}
                    />
                  </Form.Item>
                  <Form.Item label="床位" field="location">
                    <div style={{ display: "none" }}>
                      {bed[defaultData.location as keyof typeof bed]}
                    </div>
                    <Select
                      placeholder="请选择床位"
                      disabled={!selectedRoomId}
                      defaultValue={
                        bed[defaultData.location as keyof typeof bed]
                      }
                      showSearch
                      options={bedList?.map((item) => ({
                        label: item.label,
                        value: item.value,
                      }))}
                      onChange={(v) => (defaultData.location = v)}
                    />
                  </Form.Item>
                </>
              )}
            </>
          )}
          <Form.Item
            label="联系方式"
            field="phonenumber"
            rules={[
              {
                required: true,
                message: "联系方式不得为空",
              },
            ]}
          >
            <Input placeholder="请输入联系方式" />
          </Form.Item>
          {isEditElder && (
            <>
              <Form.Item label="家属名" field="contactName">
                <Input placeholder="请输入家属姓名" />
              </Form.Item>

              <Form.Item
                label="家属电话"
                field="contactPhonenumber"
                rules={[
                  {
                    validator(value, cb) {
                      const phoneNumberRegex = /^1[3-9]\d{9}$/;
                      if (!value) {
                        return cb(null);
                      }

                      const phoneNumbers = value
                        .split(",")
                        .map((num: any) => num.trim());

                      if (phoneNumbers.length > 3) {
                        return cb("最多只能输入三个电话号码");
                      }

                      for (const num of phoneNumbers) {
                        if (!phoneNumberRegex.test(num)) {
                          return cb(
                            "请输入正确格式的电话号码，每个号码用逗号分隔，最多三个。",
                          );
                        }
                      }

                      return cb(null);
                    },
                  },
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </>
          )}
          <Form.Item label="家庭地址" field="address">
            <Input.TextArea placeholder="请输入家庭住址" />
          </Form.Item>
          <Space
            className={css`
              margin-top: 16px;
              padding: 12px 0;
              display: flex;
              justify-content: end;
            `}
          >
            {isEdit && isEditPassword && (
              <Button
                type="secondary"
                htmlType="submit"
                loading={submitForm.isLoading}
                onClick={() => setIsOpenUpdatePasswordModal(true)}
                icon={<IconLock />}
              >
                修改密码
              </Button>
            )}
            <Button
              type="outline"
              htmlType="button"
              onClick={() => {
                formRef.resetFields();
                onClose?.();
              }}
              icon={<IconClose />}
            >
              取消
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={submitForm.isLoading}
              onClick={() => submitForm.mutateAsync()}
              icon={<IconCheck />}
            >
              完成
            </Button>
          </Space>
        </Form>
      ) : null}
    </Modal>
  );
};
